/*Copyright (c) [Year] [name of copyright holder]
[Software Name] is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan
PSL v2.
You may obtain a copy of Mulan PSL v2 at:
        http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.*/
let money = 10;
const itemList = [] as string[];

export function log(text: string) {
    console.log(text);
}

world.onPlayerJoin(async ({ entity }) => {
    entity.player.directMessage(`你好，${entity.player.name}，欢迎来到本地图`);
});

for (let i = 0; i < 306; ++i) {
    for (let j = 0; j < 306; ++j) {
        voxels.setVoxel(i, 8, j, 'water');
    }
}
//制作水面

world.onPlayerJoin(({ entity }) => {
    entity.onFluidEnter(() => {
    //当玩家掉到水里
        entity.position.copy(entity.player.spawnPoint);
        entity.position.y += 4;
        entity.player.directMessage('你掉到了水里');
    });
});
//碰到水面重生

for (const e of world.querySelectorAll('*')) {
    if (e.id.startsWith('存档点')) {
        e.collides = true;
        e.fixed = true;
        e.onEntityContact(({ other }) => {
            if (other.isPlayer) {
                if (other.player) {
                    other.player.directMessage('到达新的存档点，加油！');
                    other.player.spawnPoint = e.position;
                }
            }
        });
    }
}
//制作存档点

const userTable = storage.getDataStorage('userData');

async function uploadData() {
    await userTable.set('player1', {
        money: 0,
        itemList: [],
    });
    await userTable.set('gameScore', 2500);
};
uploadData();

async function addCoins(entity: GameEntity , money: number) {
    if(entity.player) {
        const current = await userTable.increment(`${entity.player.userId}`, money);
        console.log(`${entity.player.userId}的金币增加了${money},当前金币数为${current}`);
    };
}

async function dev_function(entity: GameEntity) {
    (
        entity.player as {
            dialog: (param: GameTextDialogParams) => Promise<GameDialogResponse>;
        }
    ).dialog({
        type: GameDialogType.TEXT,
        title: '提示',
        content: `功能正在开发中，敬请期待`,
    });
}

// 添加检测玩家进入或离开 x:0-64, y:0-20, z: 0-64 的区域
const start = world.addZone({
    selector: 'player',
    bounds: new GameBounds3(
        new GameVector3(0, 9, 119),
        new GameVector3(2, 20, 121)
    ),
});
// 有玩家进入区域时触发

const startTime = Date.now(); // 获取当前时间戳
let time = 0; // 用于记录玩家耗时

start.onEnter(() => {
    time = (Date.now() - startTime) / 1000; // 计算玩家耗时
    sleep(1000); // 等待 1 秒
});

const end = world.addZone({
    selector: 'player',
    bounds: new GameBounds3(
        new GameVector3(0, 9, 122),
        new GameVector3(2, 20, 124)
    ),
});

end.onEnter(async ({ entity }) => {
    if (entity.player) {
        await entity.player.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: '获胜',
            content: `${entity.player.name}，恭喜你通关游戏!`,
        });
        world.say(`${entity.player.name}到达了终点，用了 ${time} 秒`);
        entity.player.canFly = true;
    }
    dev_function(entity);
});

const redeem_codes = world.querySelector("#兑换码");
if ( redeem_codes ){
    redeem_codes.enableInteract = true;
    redeem_codes.interactRadius = 2.5;
    redeem_codes.interactHint = "兑换码";
    redeem_codes.onInteract( async ({ entity }) => {
        const resul = await entity.player.dialog<GameInputDialogParams>({
            type: GameDialogType.INPUT,
            title: "兑换码",
            content: '欢迎加入交群群！我们会不定期发送兑换码呦！\nQQ群号:972753838\n请输入兑换码:',
        });
        const surprise: (string | null)[] = [];
        if (surprise.includes(resul)) {
            const duidaoju = await entity.player.dialog<GameSelectDialogParams>({
                type: GameDialogType.SELECT,
                title: "兑换码",
                content: '你要什么道具？',
                options: ['飞行', '跳关'],
            });
            await entity.player.dialog<GameTextDialogParams>({
                type: GameDialogType.TEXT,
                title: "兑换码",
                content: `恭喜你获得道具:${duidaoju}!`,
            });
            if (duidaoju !== null) {
                if (typeof duidaoju.value === 'string') { 
                    itemList.push(duidaoju.value);
                    await addCoins(entity,50);
                }
            }
        }   else {
            await entity.player.dialog<GameTextDialogParams>({
                type: GameDialogType.TEXT,
                title: "兑换码",
                content: '没有这个兑换码',
            });
        };        
    });
};

world.onPlayerJoin(({ entity }) => {
    entity.player.onPress(async ({ button, entity }) => {
        if (button === GameButtonType.ACTION1) {
            const response = await entity.player.dialog<GameSelectDialogParams>({
                type: GameDialogType.SELECT,
                content: `你的信息:\n跑酷币:${money}\n跳关次数`,
                title: '菜单',
                options: ['我的道具', '保存', '背景音乐'],
            });
            if (response) {
                if (response.index === 0) {
                    await entity.player.dialog<GameSelectDialogParams>({
                        type: GameDialogType.SELECT,
                        title: "菜单",
                        content: '我的道具',
                        options: itemList,
                    });
                };
            };
        };
    });
});

const store_attendant = world.querySelector('#商店服务员');
if (store_attendant) {
    store_attendant.enableInteract = true; // 允许进行互动
    store_attendant.interactRadius = 3;   // 实体的互动范围
    store_attendant.interactHint = '商店服务员'; // 互动提示框显示实体的名称
    // 玩家与实体进行交互时触发
    
    store_attendant.onInteract(async ({ entity }) => {
        const commodity_ItemsList = ['飞行', '跳关'];
        const commodity_moneyList = [10, 8];
        const commodity = await entity.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT, //对话框类型为选择框
            content: `欢迎来到跑酷币商店,你有${money}跑酷币,请问你想要什么？`,
            title: '商店服务员',
            options: ['飞行(10跑酷币)', '跳关(8跑酷币)'], //选项
        });
        if (commodity) {
            const commodity_money = commodity_moneyList[commodity.index];
            const commodity_Items = commodity_ItemsList[commodity.index];
            if (money >= commodity_money) {
                await entity.player.dialog<GameTextDialogParams>({
                    type: GameDialogType.TEXT,
                    title: "商店服务员",
                    content: `恭喜你获得道具:${commodity_Items}!`,
                });
                itemList.push(commodity_Items);
                money -= commodity_money;
            }
            else {
                await entity.player.dialog<GameTextDialogParams>({
                    type: GameDialogType.TEXT,
                    title: "商店服务员",
                    content: `要买${commodity_Items}道具还差${commodity_money}跑酷币!`,
                });
            };
        };
    });
};